<?php
namespace app\index\controller;

class Anxin1
{
    /**
     * 生成二维码
     * @param unknown $string 内容
     * @param array $coifig 配置参数
     */
    function build_QRcode($string, $config = array()){

        $basedir = dirname($_SERVER['SCRIPT_FILENAME']).'/';
        $url = 'public/images/QRcode/';
        $config += array(
            'filedir' => $basedir.$url,
            'webdir' => '/'.$url,
            'logo' => '',
            'filename'=> null,
            'level' => 'H',
            'size' => 5,
        );
        if (!file_exists($config['filedir'])) mkdir($config['filedir']);
        if(!empty($config['logo']) && !file_exists($config['logo'])){
            $config['logo'] = $basedir.$config['logo'];
            file_exists($config['logo']) || $config['logo'] = '';
        }
        //图片级别
        if(!in_array($config['level'], array('L','M','Q','H'))) $config['level'] = 'H';
        $config['size'] = min(max($config['size'], 1), 10);

        include_once('phpqrcode/qrlib.php');

        if($config['filename'] === null || !empty($config['logo'])){
            ob_start();
            QRcode::png($string, false, $config['level'], $config['size'], 2);
            $imgContent = ob_get_contents();
            ob_end_clean();
        }elseif($config['filename'] === ''){
            $config['filename'] =  $config['filedir'].md5($_REQUEST['data'].'|'.$config['level'].'|'.$config['size']).'.png';
            QRcode::png($string, $config['filename'], $config['level'], $config['size'], 2);
            $imgContent = file_get_contents($config['filename']);
        }
        //如果带有logo
        if(!empty($config['logo'])){
            $QR = imagecreatefromstring($imgContent);
            $logo = imagecreatefromstring(file_get_contents($config['logo']));
            $QR_width = imagesx($QR);
            $QR_height = imagesy($QR);
            $logo_width = imagesx($logo);
            $logo_height = imagesy($logo);
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            imagepng($QR, $config['filename']);
        }
        if(!empty($config['filename'])) return $config['webdir'].basename($config['filename']);

    }

}
